import styles from './index.less'
import React from 'react'
import { myImgPropsType, myImgStateType } from '@/interfaces/types'
//练习使用类创建组件、使用state、props
class MyImg extends React.Component
    <myImgPropsType,
    myImgStateType
>
{
    constructor(props: myImgPropsType) {
        super(props)
        const width: number = Math.round(this.props.imgSize.width
            * (this.props.imgBlurMultiple
                || 1.5))
        const height: number = Math.round((this.props.imgSize.height
            && this.props.imgSize.height
            * (this.props.imgBlurMultiple
                || 1.5))
            || width)
        this.state = {
            ...this.props,
            src: this.props.placeholderSrc
                || `${this.props.src
                }?param=${width
                }y${height
                }`,
            width: width,
            height: height
        }
    }
    componentWillUnmount = () => {
        this.setState = () => {
            return;
        };
    }
    componentDidUpdate = (prevProps: myImgPropsType) => {
        if (prevProps.src !== this.props.src) {
            this.imgLoad()
        }
    }
    //预先加载img到浏览器中加载完成再导入至标签中
    componentDidMount = () => {
        this.imgLoad = () => {
            if (!this.props.disablePreLoad) {
                ((width: number, height: number) => {
                    let img = new Image()
                    img.src = `${this.props.src
                        }?param=${width
                        }y${height
                        }`
                    img.onload = (ele) => {
                        ele.stopImmediatePropagation()
                        ele.stopPropagation()
                        this.setState((preState) =>
                        ({
                            ...preState,
                            src: img.src
                        }))
                        //监听完成后必须解除监听
                        img.onload = null
                    }
                })(this.state.width, this.state.height)
            }
        }
        if (this.props.placeholderSrc) {
            this.imgLoad()
        }
    }
    render() {
        return (
            <img
                src={this.state.src}
                loading={this.state.loading}
                style={
                    this.state.style
                }
                className={this.state.className}
            />
        );
    }
}
export default MyImg